﻿using AOOR.Utilities;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Serialization;
using Website.Infrastructure;
using Website.Interfaces;

namespace Website.Models
{
    public class ArtCollection : IArtCollection
    {
        private const string paintingsFilename = "paintings.xml";
        private List<Painting> _paintings;
        private ObjectSerializer _paintingSerializer;

        public ArtCollection(string path)
        {
            _paintingSerializer = new ObjectSerializer(Path.Combine(path, paintingsFilename));
        }

        public IEnumerable<Painting> Paintings 
        {
            get
            {
                if (_paintings == null)
                {
                    _paintings = _paintingSerializer.Deserialize<List<Painting>>();
                    // show newest pictures first
                    _paintings.Reverse();
                }
                return _paintings;
            }
        }
        
        public void AddPainting(Painting painting)
        {
            if (painting.Id == 0)
            {
                painting.Id = Enumerable.Max(_paintings, m => m.Id) + 1;
            }

            _paintings.Add(painting);
            _paintingSerializer.Serialize<List<Painting>>(_paintings);
        }

        public void DeletePainting(int id)
        {
            var painting = (from p in _paintings
                            where p.Id == id
                            select p).First();

            _paintings.Remove(painting);
            _paintingSerializer.Serialize<List<Painting>>(_paintings);
        }

        public void PromotePainting(int id)
        {
            _paintings.PromoteEntry(p => p.Id == id);
            _paintingSerializer.Serialize<List<Painting>>(_paintings);
        }

        public void DemotePainting(int id)
        {
            _paintings.DemoteEntry(p => p.Id == id);
            _paintingSerializer.Serialize<List<Painting>>(_paintings);
        }
    }
}
